<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>检测是否为人脸</title>
    <script src="https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js"></script>
</head>
<body>
<h2>上传照片检测是否为人脸</h2>
<input type="file" id="imageUpload" accept="image/*" onchange="loadAndDetect()">
<div id="imageContainer"></div>
<div id="result"></div>

<script>
    async function loadModels() {
        const MODEL_URL = 'https://raw.githubusercontent.com/justadudewhohacks/face-api.js/master/weights';
        try {
            await faceapi.nets.tinyFaceDetector.loadFromUri(MODEL_URL);
            console.log('模型加载完成');
        } catch (e) {
            console.error('模型加载失败:', e);
            alert('模型加载失败，请检查网络');
        }
    }

    async function loadAndDetect() {
        const input = document.getElementById('imageUpload');
        const file = input.files[0];
        if (!file) return;

        const img = new Image();
        img.src = URL.createObjectURL(file);
        img.onload = async () => {
            console.log('图片加载完成');
            const container = document.getElementById('imageContainer');
            const resultDiv = document.getElementById('result');
            container.innerHTML = '';
            container.appendChild(img);

            // 检测是否为人脸
            const options = new faceapi.TinyFaceDetectorOptions({
                inputSize: 224, // 适合小尺寸人脸
                scoreThreshold: 0.3 // 提高检测敏感度
            });
            const detections = await faceapi.detectAllFaces(img, options);
            const isFaceDetected = detections.length > 0;

            // 显示结果
            resultDiv.innerHTML = `<p>${isFaceDetected ? '是人脸' : '不是人脸'}</p>`;
        };
        img.onerror = () => {
            alert('图片加载失败，请检查文件');
        };
    }

    loadModels();
</script>
</body>
</html>
